package com.aos.erp.common.web.error;

import com.aos.erp.common.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.WebRequest;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class AosJsonErrorAttributes extends DefaultErrorAttributes {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Map<String, Object> map = new HashMap<String, Object>();//super.getErrorAttributes(webRequest,includeStackTrace);//super.getErrorAttributes(webRequest, includeStackTrace);

        map.put("code", "-1");

        Throwable exception = getError(webRequest);
        if (exception != null) {
            if (exception instanceof BizException) {
                BizException ex = (BizException) exception;
                map.put("code", ex.getCode());
                map.put("message", ex.getMessage());
                map.put("data", "");
            } else {
                map.put("message", exception.getMessage());
                map.put("data", "");
            }
            logger.error(exception.getMessage(), exception);
        } else {
            map.put("message", "");
            map.put("data", "");
        }


        Integer status = (Integer) webRequest.getAttribute("javax.servlet.error.status_code", RequestAttributes.SCOPE_REQUEST);
        if (status != null && status.intValue() == 404) {
            map.put("message", "接口不存在");
        }

        // SpelView 需要的变量
        map.put("timestamp",Calendar.getInstance().getTime());
        map.put("error","");
        map.put("status","");

        webRequest.setAttribute("javax.servlet.error.status_code",200, RequestAttributes.SCOPE_REQUEST);

        return map;
    }

}
